﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace Beeper
{
    public class Beep : IEditableObject
    {
        public const int FREQUENCY_MAX = 32767;
        public const int FREQUENCY_MIN = 37;

        private int frequency = 500;
        public int Frequency
        {
            get { return frequency; }
            set
            {
                if (value < FREQUENCY_MIN || value > FREQUENCY_MAX)
                    throw new ArgumentOutOfRangeException("Frequency", string.Format("Value must be between {0} and {1}.", FREQUENCY_MIN, FREQUENCY_MAX));

                frequency = value;
            }
        }

        private int duration = 1000;
        public int Duration
        {
            get { return duration; }
            set
            {
                if (value <= 0)
                    throw new ArgumentOutOfRangeException("Duration", "Value must be greater than 0.");

                duration = value;
            }
        }

        public Beep() { }

        public Beep(int frequency, int duration)
        {
            this.Frequency = frequency;
            this.Duration = duration;
        }

        #region IEditableObject Members

        private Beep editingBackup;

        public void BeginEdit()
        {
            if (editingBackup == null)
            {
                editingBackup = new Beep();
                editingBackup.Frequency = this.Frequency;
                editingBackup.Duration = this.Duration;
            }
        }

        public void CancelEdit()
        {
            this.Frequency = editingBackup.Frequency;
            this.Duration = editingBackup.Duration;
        }

        public void EndEdit()
        {
            editingBackup = null;
        }

        #endregion

        public override string ToString()
        {
            return string.Format("{0} Hz / {1} ms", this.Frequency, this.Duration);
        }

        public void Play()
        {
            Console.Beep(this.Frequency, this.Duration);
        }

        public static void Play(Beep beep)
        {
            beep.Play();
        }
    }
}
